package br.com.servlet.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.model.Game;
import br.com.model.Usuario;
import br.com.model.dao.DAOFactory;
import br.com.model.dao.UsuarioDAO;

import com.google.gson.Gson;

@Controller
public class ServicoController 
{
	@RequestMapping("/gson-games")
	public void games( Integer npag, HttpServletResponse response )
	{
		Gson gb = new Gson( );
		
		if( npag == null || npag < 0 )
		{
			npag = 0;
		}
		
		List<Game> busca = DAOFactory.infDao( ).busca( "select g from Game g", npag*50, 50, Game.class );
		
		response.setContentType( "application/json" );
		
		String json = gb.toJson( busca );
		
		try 
		{
			PrintWriter writer = response.getWriter( );
			
			writer.println( json );
		} 
		catch( IOException e )
		{
			e.printStackTrace( );
		}
	}
	
	@RequestMapping("/gson-contos")
	public void contos( Integer npag, HttpServletResponse response )
	{
		InputStream resourceAsStream = getClass( ).getResourceAsStream( "/META-INF/gson-contos.txt" );
		
		response.setContentType( "application/json" );
		
		try 
		{
			String json = IOUtils.toString( resourceAsStream );
			
			PrintWriter writer = response.getWriter( );
			
			writer.println( json );
		} 
		catch( IOException e )
		{
			e.printStackTrace( );
		}
	}
	
	@RequestMapping("/cadastro-usuario")
	public void cadastrUsuario( Usuario usuario, HttpServletResponse response )
	{
		response.setContentType( "application/json" );
		
		try 
		{
			String json = "";
			
			if( DAOFactory.infDao( ).save( usuario ) )
				json = "{\"status\": \"1\", \"idUsuario\": " + usuario.getIdUsuario( ) + "}";
			else
				json = "{\"status\": \"0\"}";
			
			PrintWriter writer = response.getWriter( );
			
			writer.println( json );
		} 
		catch( IOException e )
		{
			e.printStackTrace( );
		}
	}
	
	@RequestMapping("/conto-login")
	public void contoLogin( Usuario usuario, HttpServletResponse response )
	{
		response.setContentType( "application/json" );
		
		try 
		{
			String json = "";
			
			long loginId = ((UsuarioDAO)DAOFactory.infDao( )).Login( usuario );
			
			if( loginId != -1l )
				json = "{\"status\": \"1\", \"idUsuario\": " + loginId + "}";
			else
				json = "{\"status\": \"0\"}";
			
			PrintWriter writer = response.getWriter( );
			
			writer.println( json );
		} 
		catch( IOException e )
		{
			e.printStackTrace( );
		}
	}
}